<!-- 跟进提报 -->
<template>
  <div class="has-foot-pb">
    <div class="d-header">
      <div class="d-header-top">
        <div class="round"><img src="@/assets/images/store.png" /></div>
        <span class="color-black"> {{ detail.marketName }}</span>
      </div>
      <div class="d-header-address">
        <img src="@/assets/images/position.png" />
        <div>{{ detail.address }}</div>
      </div>
      <div class="d-header-bottom">
        <div>
          市场类型：<span class="color-black">{{ getDictName('TOBE_MARKET_TYPE', detail.marketType) }}</span>
        </div>
        <div>
          市场属性：<span class="color-black">{{ getDictName('MARKET_NATURE', detail.marketNatrue) }}</span>
        </div>
      </div>
      <div class="tags">
        <span class="tag-rd">跟进日期：{{ detail.createTime }}</span>
      </div>
    </div>
    <Card class="cus-card-style" no-mg :round="false">
      <Cell
        title="上周进展程度"
        :modelValue="preWeeklyDetail.progressStage"
        default-value="--"
        readonly
        dict-type-code="CTM_MARKET_BUID_FOLLOW_UP_PROGRESS"
      />
      <FieldSelect
        v-model="formData.progressStage"
        title="本周进展程度"
        :url="`/data-dict/app/v2/dictionary/CTM_MARKET_BUID_FOLLOW_UP_PROGRESS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
        required
      />
      <!--
        detail.marketType === 'A' 开发市场
        detail.marketNatrue === 'L' 增开分店
       -->
      <FieldSelect
        v-if="detail.marketType === 'A' && detail.marketNatrue !== 'L'"
        v-model="formData.isIntendedDealer"
        title="是否有意向经销商"
        :subTitle="['A', 'B', 'C'].includes(detail.marketNatrue) ? '' : '老商整改或开分店，选择是'"
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        label-name="label"
        value-name="value"
        method="get"
        required
        clear
      />
    </Card>

    <Card v-if="[1, '1'].includes(formData.isIntendedDealer)" class="cus-card-style" no-mg :round="false">
      <FieldSelect
        v-model="formData.isPreWeekSameDealer"
        title="是否与上周意向商家信息相同"
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        label-name="label"
        value-name="value"
        method="get"
        :required="[1, '1'].includes(formData.isIntendedDealer)"
        @change="changeIsSameDealer"
        clear
      />
      <Cell
        title="商家姓名"
        v-model="formData.dealerName"
        divider
        :right="false"
        :isInput="true"
        required
        input-align="right"
        placeholder="输入商家姓名"
      />
      <Cell
        title="商家年龄"
        v-model="formData.dealerAge"
        divider
        :right="false"
        :isInput="true"
        required
        input-align="right"
        placeholder="输入商家年龄"
      />
      <FieldSelect
        v-model="formData.intentionLevel"
        title="商家意向等级"
        class="other-cell"
        subTitle="A类：确定与全友合作意向，有合作实力，有合适口岸，可快速签约;
B类：明确与全友合作意向，但可能资金不足或口岸不达标；
C类：有明确投资意向，对全友或其他竞品品牌；"
        required
        :url="`/data-dict/app/v2/dictionary/CTM_INTENTION_LEVEL`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        clear
      />
      <FieldSelect
        v-model="formData.isPayEarmestMoney"
        title="是否缴纳保证金/意向金"
        required
        label-name="label"
        value-name="value"
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        clear
      />
      <FieldDateTime
        v-model="formData.payEarmestMoneyTime"
        title="保证金缴纳时间"
        placeholder="选择保证金缴纳日期"
        type="date"
        :default-date="formData.payEarmestMoneyTime"
        clear
        :required="[1, '1'].includes(formData.isPayEarmestMoney)"
      />
      <Cell title="现经营品牌/行业资历" is-column custom divider :right="false" required>
        <qmp-field
          v-model="formData.industryQualification"
          type="textarea"
          placeholder="输入现经营品牌/行业资历"
          class="ctm-text-area"
        />
      </Cell>
      <!-- <Cell title="是否到店/公司参观" :custom="true" :right="false" required>
        <qmp-switch v-model="formData.isArriveShore" :active-value="1" :inactive-value="0">
          <template #background>
            <span class="qmp-switch__background"> {{ formData.isArriveShore === 1 ? '是' : '否' }}</span>
          </template>
        </qmp-switch>
      </Cell> -->

      <FieldSelect
        v-model="formData.isArriveShore"
        title="是否到店/公司参观"
        required
        label-name="label"
        value-name="value"
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        clear
      />
      <Cell
        title="预算投入金额"
        v-model="formData.budgetedAmount"
        divider
        :right="false"
        :isInput="true"
        required
        input-align="right"
        placeholder="输入金额"
        unit="万"
      />
    </Card>
    <!-- marketType 市场类型（B:整改市场,A 开发市场） -->
    <Card
      v-if="[1, '1'].includes(formData.isIntendedDealer) || (detail.marketType === 'A' && detail.marketNatrue === 'L')"
      class="cus-card-style"
      no-mg
      :round="false"
    >
      <template v-if="detail.marketType === 'A' && detail.marketNatrue === 'L'">
        <!-- 市场类型为开发市场(marketType=A)，市场属性为增开分店(marketNatrue=L)时，此处区域都显示 -->
        <FieldSelect
          v-model="formData.isPayEarmestMoney"
          title="是否缴纳保证金/意向金"
          label-name="label"
          value-name="value"
          :optionData="[
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ]"
          required
          clear
        />
        <FieldDateTime
          v-model="formData.payEarmestMoneyTime"
          title="保证金缴纳时间"
          placeholder="选择保证金缴纳日期"
          type="date"
          :default-date="formData.payEarmestMoneyTime"
          :required="[1, '1'].includes(formData.isPayEarmestMoney)"
          clear
        />
      </template>
      <FieldSelect
        v-model="formData.isSuitableSite"
        title="是否有合适场地"
        label-name="label"
        value-name="value"
        method="get"
        required
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        clear
      />
      <template v-if="[1, '1'].includes(formData.isSuitableSite)">
        <FieldSelect
          v-model="formData.isPreWeekSameSite"
          title="是否与上周场地信息相同"
          :optionData="[
            { label: '是', value: 1 },
            { label: '否', value: 0 }
          ]"
          label-name="label"
          value-name="value"
          method="get"
          required
          @change="changeIsSameSite"
        />

        <Cell
          title="预估面积(㎡)"
          v-model="formData.estimatedArea"
          divider
          :right="false"
          :isInput="true"
          :required="true"
          input-align="right"
          placeholder="输入预估面积"
        />
        <Cell
          title="场地详细地址"
          is-column
          custom
          divider
          :right="false"
          :required="[1, '1'].includes(formData.isSuitableSite)"
        >
          <qmp-field v-model="formData.address" type="textarea" placeholder="输入场地详细地址" class="ctm-text-area" />
        </Cell>
        <Cell
          title="请补充完末级地址信息，如区县、街道、xx路、xx号"
          :custom="true"
          isColumn
          :right="false"
          cellClassName="redTips"
        />
      </template>
    </Card>
    <Card class="cus-card-style" no-mg :round="false">
      <FieldSelect
        v-model="formData.isCurrentMonthMakeMap"
        title="本月是否可测绘"
        label-name="label"
        value-name="value"
        :optionData="[
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ]"
        clear
        required
      />
      <FieldDateTime
        v-model="formData.estimatedSurveyTime"
        title="预计测绘时间"
        placeholder="选择预计测绘时间"
        type="date"
        clear
        :required="[1, '1'].includes(formData.isCurrentMonthMakeMap)"
      />
    </Card>

    <Card class="cus-card-style" no-mg :round="false">
      <Cell title="跟进说明" is-column custom divider :right="false" required>
        <qmp-field v-model="formData.remark" type="textarea" placeholder="填写跟进说明" class="ctm-text-area" />
      </Cell>
      <Cell
        title="无进展时，请详细描述开展计划、市场情况、陌拜结果、人口、楼盘等情况"
        :custom="true"
        isColumn
        :right="false"
        cellClassName="redTips"
      />
    </Card>

    <Card title="最后一次审核结果" no-mg :round="false">
      <Cell
        class="more-class"
        title="审核结果"
        :modelValue="detail.aduitStatus"
        dict-type-code="REVIEW_RESULT"
        default-value="--"
        readonly
      />
      <Cell class="more-class" title="审核意见" :modelValue="detail.aduitFialRemark" default-value="" readonly custom />
    </Card>

    <Card v-if="preWeeklyDetail && preWeeklyDetail.id" title="上周最后一次审核结果" no-mg :round="false">
      <Cell
        class="more-class"
        title="审核结果"
        :modelValue="preWeeklyDetail.aduitStatus"
        dict-type-code="REVIEW_RESULT"
        default-value="--"
        readonly
      />
      <Cell
        class="more-class"
        title="审核意见"
        :modelValue="preWeeklyDetail.aduitFialRemark"
        default-value=""
        readonly
        custom
      />
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit">提交</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import Card from '@/components/Card/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  // import Card from '@/components/Card/index.vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { marketDataDetail, submit } from '@/apis/storeUpgrade/index'
  import { initFormData, isChange } from '@/utils'
  import { getDictByPatchType } from '@/apis/dataDict'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    id: any
    dictParams: object
    formData: any
    originalData: string
    detail: any
    dictData: any
    submiting: boolean
    isEditBack: boolean
    [key: string]: any
  }
  const none: any[] = [undefined, null, '']
  export default {
    name: 'StoreUpgradeTaskEdit',
    components: { Card, Cell, FieldSelect, FieldDateTime },
    setup() {
      const $route = useRoute()
      const $router = useRouter()
      const { proxy }: any = getCurrentInstance()

      const state = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          id: '',
          progressStage: '',
          isIntendedDealer: '',
          isPreWeekSameDealer: '', // 是否与上周意向商家信息相同
          dealerName: '',
          dealerAge: '',
          intentionLevel: '',
          isPayEarmestMoney: '',
          payEarmestMoneyTime: '',
          industryQualification: '',
          isArriveShore: '',
          budgetedAmount: '',
          isSuitableSite: '',
          isPreWeekSameSite: '', //是否与上周卖场信息相同
          estimatedArea: '',
          address: '',
          isCurrentMonthMakeMap: '', //本月是否可测绘
          estimatedSurveyTime: '',
          remark: ''
        },
        originalData: '', // 原始数据 用于对比值是否发生变化
        detail: {},
        dictData: {},
        submiting: false,
        isEditBack: false // 是否是编辑成功后返回
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()
      const preWeeklyDetail = computed(() => {
        // 上周任务信息
        return state.detail.preCtmMarketWeeklyAppDetailDTO || {}
      })

      // 阻止返回
      onBeforeRouteLeave((to, from, next) => {
        if (state.isEditBack || isChange(state.formData, state.originalData)) next()
        else {
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }
      })

      const onSubmit = () => {
        if (state.submiting) return
        const data = { ...state.formData }

        if (none.includes(data.progressStage)) {
          proxy.$toast('请选择本周进展程度')
          return
        }
        if (state.detail.marketType === 'A' && state.detail.marketNatrue !== 'L') {
          if (none.includes(data.isIntendedDealer)) {
            proxy.$toast('请选择是否有意向经销商')
            return
          }
        }

        if ([1, '1'].includes(data.isIntendedDealer)) {
          if (none.includes(data.isPreWeekSameDealer)) {
            proxy.$toast('请选择是否与上周意向商家信息相同')
            return
          }

          if (none.includes(data.dealerName)) {
            proxy.$toast('请输入商家姓名')
            return
          }

          if (none.includes(data.dealerAge)) {
            proxy.$toast('请输入商家年龄')
            return
          }

          // let regAge = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
          // if (data.dealerAge && !regAge.test(data.dealerAge)) {
          //   proxy.$toast('年龄输入不合法')
          //   return
          // }

          if (none.includes(data.intentionLevel)) {
            proxy.$toast('请选择商家意向等级')
            return
          }

          if (none.includes(data.isPayEarmestMoney)) {
            proxy.$toast('请选择是否缴纳保证金/意向金')
            return
          }
          if ([1, '1'].includes(data.isPayEarmestMoney) && none.includes(data.payEarmestMoneyTime)) {
            proxy.$toast('请选择保证金缴纳时间')
            return
          }

          if (none.includes(data.industryQualification)) {
            proxy.$toast('请输入现经营品牌/行业资历')
            return
          }

          if (none.includes(data.budgetedAmount)) {
            proxy.$toast('请输入预算投入金额')
            return
          }
          const regPrice = /^[0-9]*[1-9][0-9]*$/
          if (data.budgetedAmount && !regPrice.test(data.budgetedAmount)) {
            proxy.$toast('预算投入金额输入不合法')
            return
          }
        }
        if (state.detail.marketType === 'A' && state.detail.marketNatrue === 'L') {
          // 仅市场类型为：开发市场、属性为增开分店时
          if (none.includes(data.isPayEarmestMoney)) {
            proxy.$toast('请选择是否缴纳保证金/意向金')
            return
          }
          if ([1, '1'].includes(data.isPayEarmestMoney) && none.includes(data.payEarmestMoneyTime)) {
            proxy.$toast('请选择保证金缴纳时间')
            return
          }
        }
        if (
          [1, '1'].includes(data.isIntendedDealer) ||
          (state.detail.marketType === 'A' && state.detail.marketNatrue === 'L')
        ) {
          if (none.includes(data.isSuitableSite)) {
            proxy.$toast('请选择是否有合适场地')
            return
          }

          if (data.isSuitableSite === 1) {
            if (none.includes(data.isPreWeekSameSite)) {
              proxy.$toast('请选择是否与上周场地信息相同')
              return
            }

            if (none.includes(data.estimatedArea)) {
              proxy.$toast('请输入预估面积')
              return
            }
            const regArea = /^[1-9][0-9]*([\.][0-9]{1,2})?$/
            if (data.estimatedArea && !regArea.test(data.estimatedArea)) {
              proxy.$toast('预估面积输入不合法')
              return
            }
            if (none.includes(data.address)) {
              proxy.$toast('请输入场地详细地址')
              return
            }
          }
        }
        if ([1, '1'].includes(data.isCurrentMonthMakeMap)) {
          if (none.includes(data.estimatedSurveyTime)) {
            proxy.$toast('请选择预计测绘时间')
            return
          }
        }
        const remark = `${data.remark || ''}`.trim()
        if (none.includes(remark)) {
          proxy.$toast('请输入跟进说明')
          return
        }
        if (![1, '1'].includes(data.isIntendedDealer)) {
          data.isPreWeekSameDealer = 0
        }
        if (![1, '1'].includes(data.isSuitableSite)) {
          data.isPreWeekSameSite = 0
        }

        state.submiting = true
        submit(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast('提报成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
              state.submiting = false
            }
          })
          .catch((e: any) => {
            if (e) proxy.$toast(e)
            state.submiting = false
          })
      }

      const getDictName = (dictType: string, code: any) => {
        if (!dictType || [undefined, null, ''].includes(code)) return ''
        let name = code
        const dictList = state.dictData[dictType] || []
        if (dictList.length > 0) {
          const obj = dictList.find((v: any) => v.dictCode === `${code}`)
          name = obj?.dictName || code
        }
        return name
      }

      const getDetail = () => {
        const id = `${state.id}`
        marketDataDetail(id).then((res: any) => {
          state.detail = res.data
          initFormData(res.data, state.formData)
          const toNumberFields = [
            'isIntendedDealer',
            'isPayEarmestMoney',
            'isArriveShore',
            'isSuitableSite',
            'isPreWeekSameDealer',
            'isCurrentMonthMakeMap',
            'isPreWeekSameSite'
          ]
          toNumberFields.forEach((k) => {
            if (none.includes(res.data[k])) {
              state.formData[k] = ''
            }
          })

          state.originalData = JSON.stringify(state.formData)
          if (state.detail.marketType === 'A' && state.detail.marketNatrue === 'L') {
            const sameFields = ['isPayEarmestMoney', 'payEarmestMoneyTime', 'budgetedAmount', 'estimatedArea']
            sameFields.forEach((k) => {
              state.formData[k] = ![null, undefined, ''].includes(preWeeklyDetail.value[k])
                ? preWeeklyDetail.value[k]
                : ''
            })
          }
          if (![1, '1'].includes(state.formData.isPreWeekSameSite)) {
            state.formData.estimatedArea = ''
          }
        })
      }
      getDetail()
      // 获取数据字典
      const getDictData = async () => {
        const dictTypeCodes = [
          // 'CTM_MARKET_BUID_FOLLOW_UP_PROGRESS',
          'TOBE_MARKET_TYPE',
          // 'CTM_MARKET_BUID_WEEK_MAINTENANCE_PROGRESS',
          // 'CTM_INTENTION_LEVEL'
          'MARKET_NATURE'
          // 'CTM_MARKET_DATA_FROM',
          // 'CTM_APPRAISAL_PLAN'
        ]
        state.dictData = await getDictByPatchType({ dictTypeCodes })
      }

      const changeIsSameDealer = (data: any) => {
        const sameFields = [
          'dealerName',
          'dealerAge',
          'intentionLevel',
          'isPayEarmestMoney',
          'payEarmestMoneyTime',
          'industryQualification',
          'isArriveShore',
          'budgetedAmount'
        ]
        sameFields.forEach((k) => {
          if ([1, '1'].includes(data.value)) {
            state.formData[k] = ![null, undefined, ''].includes(preWeeklyDetail.value[k])
              ? preWeeklyDetail.value[k]
              : ''
          } else {
            state.formData[k] = ''
          }
        })
      }

      const changeIsSameSite = (data: any) => {
        if (state.detail.marketType === 'A' && state.detail.marketNatrue === 'L') {
          const sameFields = ['isPayEarmestMoney', 'payEarmestMoneyTime', 'budgetedAmount']
          sameFields.forEach((k) => {
            if ([1, '1'].includes(data.value)) {
              state.formData[k] = ![null, undefined, ''].includes(preWeeklyDetail.value[k])
                ? preWeeklyDetail.value[k]
                : ''
            } else {
              state.formData[k] = ''
            }
          })
        }
        const otherFileds = ['estimatedArea', 'address']
        otherFileds.forEach((k) => {
          if ([1, '1'].includes(data.value)) {
            state.formData[k] = ![null, undefined, ''].includes(preWeeklyDetail.value[k])
              ? preWeeklyDetail.value[k]
              : ''
          } else {
            state.formData[k] = ''
          }
        })
      }

      getDictData()
      return {
        ...toRefs(state),
        preWeeklyDetail,
        onSubmit,
        getDictName,
        changeIsSameDealer,
        changeIsSameSite
      }
    }
  }
</script>

<style lang="less" scoped>
  .d-header {
    padding: 14px;
    background-color: var(--bg-global-weaker);
    margin: 8px 0;
    .d-header-top {
      display: flex;
      align-items: center;
      height: 24px;
      font: var(--font-main-title-strengthen);
      .round {
        width: 24px;
        height: 24px;
        background: var(--texticon-color-warning-normal);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }

    .d-header-address {
      display: flex;
      align-items: center;
      margin-top: 4px;
      height: 24px;
      font: var(--font-main-body);
      color: var(--texticon-default-stronger);

      img {
        width: 20px;
        height: 20px;
        margin-right: 8px;
        padding: 2px;
      }
    }

    .d-header-bottom {
      font: var(--font-main-body);
      color: var(--texticon-default-stronger);

      div {
        margin: 8px 0;
        width: calc(100% - 100px);
      }
    }

    .tags {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .tag-rd {
        display: inline-flex;
        padding: 4px 8px;
        margin-right: 4px;
        border-radius: 2px;
        background: var(--bg-focusing-brand);
        font: var(--font-main-body);
        color: var(--texticon-color-brand-normal);
      }
    }
  }

  .header {
    margin-top: 8px;
    height: 20px;
    font: var(--font-main-body);
    color: var(--texticon-default-stronger);
    background: var(--bg-global-weaker);
    padding: 8px 14px;
    position: relative;

    &::after {
      position: absolute;
      content: '';
      width: calc(100% - 28px);
      height: 1px;
      bottom: 0;
      left: 14px;
      background: var(--divisionline-weak);
    }
  }

  .is-dealer {
    /deep/ .c-cell {
      background: var(--bg-global-normal);
    }
  }
  .more-class {
    /deep/ .label {
      color: var(--texticon-default-strong) !important;
    }
  }

  .redTips {
    /deep/ .black {
      color: var(--texticon-color-error-normal) !important;
    }
  }
  .other-cell {
    /deep/ .sub-label {
      width: 240px;
      white-space: pre-wrap;
    }
  }
  .cus-card-style {
    padding: 0;
    border-radius: 0;
    margin-left: 0;
    margin-right: 0;
  }
</style>
